package com.kehao.leetcode.jzoffer;

import org.junit.Test;

/**
 * @author Kehao.Chen
 * @version 1.0
 * @date 2022/6/22 17:57
 */
public class JZSolution021 {

    private static class ListNode {
        int val;
        ListNode next;
        ListNode() {
        }
        ListNode(int val) {
            this.val = val;
        }
        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode h = new ListNode();
        h.next = head;
        ListNode pre = h;
        ListNode p = head;
        for (int i = 0; i < n; i++) {
            p = p.next;
        }
        while (p!=null){
            p = p.next;
            pre = pre.next;
        }
        pre.next = pre.next.next;
        return h.next;
    }

    @Test
    public void test01(){
        int[] arr = new int[]{1,2,3,4,5};
        ListNode h = new ListNode();
        ListNode p = h;
        for (int i = 0; i < arr.length; i++) {
            ListNode listNode = new ListNode(arr[i]);
            p.next = listNode;
            p = p.next;
        }
        ListNode head = h.next;
        removeNthFromEnd(head,2);
    }
}
